package com.xncoding.freemarker.ctr;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xncoding.freemarker.utile.SFtpUtil;
import com.xncoding.freemarker.utile.SftpVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: SftpController
 * @Description: 上传sftp通用
 * @author: huangyao
 * @date: 2020/5/20 10:19
 */

@RestController
public class SftpController {
    protected Log log = LogFactory.getLog(UploadSftpController.class);

    @RequestMapping("/hello")
    public String helloWorld() {
        log.info("helloWorld");
        return "helloWorld";
    }

    @RequestMapping("/uploadWithSftp")
    public Map uploadWithSftp(@RequestBody Map<String, String> params) {
        log.info("上传文件参数："+JSON.toJSONString(params));
        Map<String, String> response = new HashMap<>();
        String fileData = params.get("fileData");//数据字符串
        String filePath = params.get("filePath");//上传相对路径
        String fileName = params.get("fileName");//文件名
        String sftpIp = params.get("sftpIp");//sftp-ip
        int sftpPort = Integer.valueOf(params.get("sftpPort"));//sftp-端口
        String sftpUserName = params.get("sftpUserName");//用户名
        String sftpPassword = params.get("sftpPassword");//密码
        String sftpPath = params.get("sftpPath");//sftp根路径
        String serverPath = params.get("serverPath");//本地存放路径
        String privateKeyPath = params.get("privateKeyPath");//登录私钥存放路径,包含文件名
        try {
            //生成本地文件
            createFile(serverPath, fileName, fileData);
            //上传京东sftp
            SftpVo sftpVo = new SftpVo();
            sftpVo.setIp(sftpIp);
            sftpVo.setPort(sftpPort);
            sftpVo.setUser(sftpUserName);
            sftpVo.setPassword(sftpPassword);
            sftpVo.setUploadSftpDirName(sftpPath + filePath);
            sftpVo.setUploadDirName(serverPath);
            sftpVo.setFileName(fileName);
            sftpVo.setPrivateKeyPath(privateKeyPath);
            sftpVo.setFlagPrivateKeyPath("1");//1  为绝对路径   0为相对路径。
            try {
                if (SFtpUtil.uploadFile(sftpVo)) {
                    log.info("上传成功,保存路径" + sftpVo.getUploadSftpDirName() + fileName);
                    response.put("result", "success");
                } else {
                    log.info("上传失败");
                    response.put("result", "fail");
                    response.put("message", "上传失败");
                }
            } catch (Exception e) {
                response.put("result", "fail");
                response.put("message", "上传失败");
                log.error(e);
            }
        } catch (Exception e) {
            response.put("result", "fail");
            response.put("message", "上传失败");
            log.error(e);
        } finally {
            File file = new File(serverPath + fileName);
            if (file.exists()) {
                boolean delete = file.delete();
                log.info("上传SFTP后删除文件:" + serverPath + fileName + "," + (delete ? "成功" : "失败"));
            }
        }
        log.info("uploadWithSftp返回参数："+JSON.toJSONString(response));
        return response;
    }

    @RequestMapping("/downloadWithSftp")
    public Map downloadWithSftp(@RequestBody Map<String, String> params) {
        log.info("单个文件下载参数："+JSON.toJSONString(params));
        Map<String, String> resultMap = new HashMap<>();
        String filePath = null;
        //文件名
        String fileName = params.get("fileName");
        //sftp-ip
        String sftpIp = params.get("sftpIp");
        //sftp-端口
        int sftpPort = Integer.parseInt(params.get("sftpPort"));
        //用户名
        String sftpUserName = params.get("sftpUserName");
        //密码
        String sftpPassword = params.get("sftpPassword");
        //sftp根路径
        String sftpPath = params.get("sftpPath");
        //本地存放路径
        String serverPath = params.get("serverPath");
        //登录私钥存放路径,包含文件名
        String privateKeyPath = params.get("privateKeyPath");
        try {
            //从度小满sftp下载文件
            SftpVo sftpVo = new SftpVo();
            sftpVo.setIp(sftpIp);
            sftpVo.setPort(sftpPort);
            sftpVo.setUser(sftpUserName);
            sftpVo.setPassword(sftpPassword);
            sftpVo.setDownloadDirName(serverPath);
            sftpVo.setSftpDir(sftpPath);
            sftpVo.setFileName(fileName);
            sftpVo.setPrivateKeyPath(privateKeyPath);
            //1  为绝对路径   0为相对路径。
            sftpVo.setFlagPrivateKeyPath("1");
            try {
                if (!SFtpUtil.isFileExist(sftpVo)) {
                    log.info("文件下载失败，文件不存在{}" + fileName);
                    resultMap.put("result", "fail");
                    resultMap.put("message", "文件下载失败，文件不存在");
                    return resultMap;
                }
                //下载文件
                SFtpUtil.sftpDownload(sftpVo);
                filePath = sftpVo.getDownloadDirName() + fileName;
                log.info("下载文件成功,保存路径" + filePath);
                String data = readFileContent(filePath);
                resultMap.put("data", data);
                resultMap.put("result", "success");
                resultMap.put("message", "交易成功");
            } catch (Exception e) {
                resultMap.put("result", "fail");
                resultMap.put("message", "下载失败");
                log.error(e);
            }
        } catch (Exception e) {
            resultMap.put("result", "fail");
            resultMap.put("message", "下载失败");
            log.error(e);
        } finally {
            File file = new File(serverPath + fileName);
            if (file.exists()) {
                boolean delete = file.delete();
                log.info("读取文件后删除文件:" + serverPath + fileName + "," + (delete ? "成功" : "失败"));
            }
        }
        log.info("downloadWithSftp返回参数："+JSON.toJSONString(resultMap));
        return resultMap;
    }

    public boolean createFile(String filePath, String fileName, String data) {

        File dir = new File(filePath);
        // 一、检查放置文件的文件夹路径是否存在，不存在则创建
        if (!dir.exists()) {
            dir.mkdirs();// mkdirs创建多级目录
        }
        File checkFile = new File(filePath + fileName);
        FileWriter writer = null;
        try {
            // 二、检查目标文件是否存在，不存在则创建
            if (!checkFile.exists()) {
                checkFile.createNewFile();// 创建目标文件
            }
            // 三、向目标文件中写入内容
            // FileWriter(File file, boolean append)，append为true时为追加模式，false或缺省则为覆盖模式
            writer = new FileWriter(checkFile, false);
            writer.append(data);
            writer.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (null != writer) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr).append(System.lineSeparator());
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }
}
